package com.ipdatacloud.search;

import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;

public class AccessLocation {
    private final Search ipv4Search;
    private final Search ipv6Search;


    AccessLocation(String ipv4Database, String ipv6Database) throws IOException {
        this.ipv4Search = Search.getIpv4InstanceLocationMemory(ipv4Database);
        this.ipv6Search = Search.getIpv6InstanceMemory(ipv6Database);
    }

    public Location get(InetAddress address) {
        String result = "";
        if (address instanceof Inet4Address) {
            try {
                result = this.ipv4Search.get(address);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else if (address instanceof Inet6Address) {
            try {
                result = this.ipv6Search.get(address);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        } else {
            throw new IllegalArgumentException("Invalid ip address");
        }
        return new Location(result);
    }

    public static void main(String[] args) throws IOException {
        AccessLocation access = new AccessLocation("D:\\databases\\ipdatacloud_city.dat", "D:\\databases\\ipv6_city.dat");
        Location location = access.get(InetAddress.getByName("::ffff:1.13.14.76"));
        System.out.println(location.getCity());
    }

}
